<?php
/**
 *
 * @author Martin "DevelX" Jurča
 */
class Banners extends Module {
    protected $name = 'Banners';
    protected $administrable = true;
    protected $version = '2010-02-12';
    protected $details = array('dependencies' => array(),
            'observes' => array('Banners'));

    const AREAS = 'bannersAreas';
    const BANNERS = 'banners';

    protected $areasTable = array('id' => 'iPN+', 'label' => "v'255'UN",
            'bannersCount' => 'iN', 'code' => "v'4096'");
    protected $bannersTable = array('id' => 'iPN+', 'title' => 's', 'area' =>
            'iNI', 'type' => 'iN', 'link' => "v'4096'", 'value' => "v'4096'",
            'views' => 'iN', 'viewsLeft' => 'iN');

    protected $areaRecord = array('table' => self::AREAS, 'data' => array());
    protected $bannerRecord = array('table' => self::BANNERS, 'data' =>
            array());

    public function __construct(DBAPI $dbapi, RecordList $recordList) {
        parent::__construct($dbapi, $recordList);
        $this->areaRecord['properties'] = $this->areasTable;
        $this->bannerRecord['properties'] = $this->bannersTable;
    }

    public function install() {
        Modules::getModule('Users')->registerRights($this->getName(),
                $this->getRights());
        return $this->dbdriver->createTable(self::AREAS, $this->areasTable) &&
                $this->dbdriver->createTable(self::BANNERS,
                $this->bannersTable);
    }

    public function uninstall() {
        return $this->dbdriver->dropTable(self::AREAS) &&
                $this->dbdriver->dropTable(self::BANNERS);
    }

    public function getBannerCount($area) {
        $cols = array('id');
        $area = &$this->dbdriver->select(self::AREAS, $cols, '`label` = \'' .
                $this->dbdriver->escapeString($area) . '\'');
        if (!isset($area[0])) {
            return 0;
        }
        $cols = array('COUNT(`id`)');
        $count = &$this->dbdriver->select(self::BANNERS, $cols,
                '`area` = ' . $area[0]['id']);
        return $count[0]['COUNT(`id`)'];
    }

    public function onAddArea(&$details, $source) {
        if (!$this->hasRights('create area')) {
            return;
        }
        $area = $this->fillRecord($this->areaRecord, $details);
        $this->dbapi->save($area);
        Kernel::setRedirect($this->getLink('areas/'));
    }

    public function onDeleteArea(&$details, $source) {
        Kernel::setRedirect($this->getLink('areas/'));
        if (!$this->hasRights('delete area')) {
            return;
        }
        $this->dbdriver->delete(self::BANNERS, '`area` = ' . (int) $details);
        $this->dbdriver->delete(self::AREAS, '`id` = ' . (int) $details);
    }

    public function onEditArea(&$details, $source) {
        if (!$this->hasRights('edit area')) {
            return;
        }
        $area = $this->fillRecord($this->areaRecord, $details);
        $this->dbapi->update($area);
        Kernel::setRedirect($this->getLink('areas/'));
    }

    public function onAddBanner(&$details, $source) {
        if (!$this->hasRights('create banner')) {
            return;
        }
        $banner = $this->fillRecord($this->bannerRecord, $details);
        if ($details['type'] == 0) {
            $banner['data']['value'] = serialize(array('src' =>
                    $details['flashSrc'], 'width' => $details['flashWidth'],
                    'height' => $details['flashHeight'], 'class' =>
                    $details['flashClass'], 'quality' =>
                    $details['flashQuality'], 'wmode' =>
                    $details['flashWMode'], 'menu' => $details['flashMenu']));
        } elseif ($details['type'] == 1) {
            $banner['data']['value'] = serialize(array('width' =>
                    $details['flashWidth'], 'height' =>
                    $details['flashHeight'], 'src' => $details['flashSrc']));
        }
        $banner['data']['views'] = 0;
        $this->dbapi->save($banner);
    }

    public function onDeleteBanner(&$details, $source) {
        Kernel::setRedirect($this->getLink());
        if (!$this->hasRights('delete banner')) {
            return;
        }
        $this->dbdriver->delete(self::BANNERS, '`id` = ' . (int) $details);
    }

    public function onEditBanner(&$details, $source) {
        if (!$this->hasRights('edit banner')) {
            return;
        }
        $banner = $this->bannerRecord;
        $banner['data']['id'] = (int) $details['id'];
        $this->dbapi->refresh($banner);
        $banner = $this->fillRecord($banner, $details);
        if ($details['type'] == 0) {
            $banner['data']['value'] = serialize(array('src' =>
                    $details['flashSrc'], 'width' => $details['flashWidth'],
                    'height' => $details['flashHeight'], 'class' =>
                    $details['flashClass'], 'quality' =>
                    $details['flashQuality'], 'wmode' =>
                    $details['flashWMode'], 'menu' => $details['flashMenu']));
        } elseif ($details['type'] == 1) {
            $banner['data']['value'] = serialize(array('width' =>
                    $details['flashWidth'], 'height' =>
                    $details['flashHeight'], 'src' => $details['flashSrc']));
        }
        $this->dbapi->update($banner);
    }

    public function displayBlank($param = null) {
        $params = array('filter' => '`label` = \'' .
                $this->dbdriver->escapeString($param) . '\'');
        $area = &$this->recordList->getList($this->areaRecord, $params);
        if (!isset($area[0])) {
            echo "<!-- banner area $param not found! -->";
            return;
        }
        $area = $area[0];
        $allBanners = &$this->dbapi->load($this->bannerRecord, '`area` = ' .
                $area['id'] . ' AND (`viewsLeft` > 0 OR `viewsLeft` = -1)');
        $count = count($allBanners) - 1;
        $banners = array();
        for ($i = 0; $i < $area['bannersCount']; $i++) {
            $banners[] = &$allBanners[rand(0, $count)];
        }
        $parts = explode('__BANNER__', $area['code']);
        echo $parts[0];
        foreach ($banners as &$banner) {
            if (!isset($banner['data'])) {
                continue;
            }
            $params = array_merge(unserialize($banner['data']['value']),
                    $banner['data']);
            if ($banner['data']['type'] == 0) {
                $this->template('flash', $params);
            } elseif ($banner['data']['type'] == 1) {
                $this->template('image', $params);
            }
            $banner['data']['views'] += 1;
            $banner['data']['viewsLeft'] -= $banner['data']['viewsLeft'] > -1 ?
                    1 : 0;
            $this->dbapi->update($banner);
        }
        echo $parts[1];
    }

    public function displayAdminEditBanner($id) {
        if (!$this->hasRights('edit banner')) {
            return;
        }
        $banner = $this->bannerRecord;
        $banner['data']['id'] = (int) $id;
        $this->dbapi->refresh($banner);
        $banner = $banner['data'];
        $form = $this->getBannerForm('addBanner');
        $form['items'][] = array('name' => 'id', 'value' => $banner['id'],
                'type' => 'hidden');
        $form['items'][0]['selected'] = $banner['area'];
        $form['items'][1]['value'] = $banner['title'];
        $form['items'][2]['value'] = $banner['viewsLeft'];
        $value = unserialize($banner['value']);
        if ($banner['type'] == 0) {
            $form['items'][3]['checked'] = true;
            $form['items'][5]['value'] = $value['src'];
            $form['items'][6]['value'] = $value['width'];
            $form['items'][7]['value'] = $value['height'];
            $form['items'][8]['value'] = $value['class'];
            $form['items'][9]['value'] = $value['quality'];
            $form['items'][10]['value'] = $value['wmode'];
            $form['items'][11]['value'] = $value['menu'];
        } elseif ($banner['type'] == 1) {
            $form['items'][4]['checked'] = true;
            $form['items'][5]['value'] = $value['src'];
            $form['items'][6]['value'] = $value['width'];
            $form['items'][7]['value'] = $value['height'];
        }
        $form['items'][12]['value'] = $banner['link'];
        $form['start'] = 'editBanner';
        $this->prepareFormData($form);
        $params = array('form' => &$form);
        $this->template('form', $params);
    }

    public function displayAdminIndex() {
        $params = array('order' => array('id'));
        $banners = &$this->recordList->getList($this->bannerRecord, $params);
        foreach ($banners as &$banner) {
            $banner['label'] = $banner['title'];
            $banner['edit'] = $this->getLink("edit-banner/{$banner['id']}/");
            $banner['delete'] = $this->getLink($banner['id'], 'deleteBanner');
        }
        $params = array('items' => &$banners);
        $this->template('list', $params);
    }

    public function displayAdminAddBanner() {
        if (!$this->hasRights('create banner')) {
            return;
        }
        $form = $this->getBannerForm('addBanner');
        $this->prepareFormData($form);
        $params = array('form' => &$form);
        $this->template('form', $params);
    }

    public function displayAdminEditArea($id) {
        if (!$this->hasRights('edit area')) {
            return;
        }
        $area = $this->areaRecord;
        $area['data']['id'] = (int) $id;
        $this->dbapi->refresh($area);
        $form = array('start' => 'editArea', 'submit' => 'save', 'legend' =>
                'editAreaForm', 'items' => array(array('name' => 'id',
                'type' => 'hidden', 'value' => $area['data']['id']),
                array('name' => 'label', 'label' => 'label', 'value' =>
                $area['data']['label']), array('name' => 'bannersCount',
                'label' => 'bannersCount', 'value' =>
                $area['data']['bannersCount']), array('name' => 'code',
                'label' => 'code', 'value' => $area['data']['code'], 'type' =>
                'textarea', 'cols' => 80, 'rows' => 6)));
        $this->prepareFormData($form);
        $params = array('form' => &$form);
        $this->template('form', $params);
    }

    public function displayAdminAreas() {
        $params = array();
        $areas = &$this->recordList->getList($this->areaRecord, $params);
        foreach ($areas as &$area) {
            $area['edit'] = $this->getLink("edit-area/{$area['id']}/");
            $area['delete'] = $this->getLink($area['id'], 'deleteArea');
        }
        $params = array('items' => &$areas);
        $this->template('list', $params);
    }

    public function displayAdminAddArea() {
        if (!$this->hasRights('create area')) {
            return;
        }
        $form = array('start' => 'addArea', 'submit' => 'add', 'legend' =>
                'addAreaForm', 'items' => array(array('name' => 'label',
                'label' => 'label'), array('name' => 'bannersCount', 'label' =>
                'bannersCount'), array('name' => 'code', 'label' => 'code',
                'type' => 'textarea', 'cols' => '80', 'rows' => '6')));
        $this->prepareFormData($form);
        $params = array('form' => &$form);
        $this->template('form', $params);
    }

    public function displayAdminSubmenu() {
        $menu = array(array('label' => 'listBanner', 'href' => ''),
                array('label' => 'addBanner', 'href' => 'add-banner/'),
                array('label' => 'listAreas', 'href' => 'areas/'),
                array('label' => 'addArea', 'href' => 'add-area/'));
        $this->prepareMenu($menu);
        $params = array('menu' => &$menu);
        $this->template('submenu', $params);
    }

    private function getBannerForm($event) {
        $areas = array();
        $params = array('order' => array('id'));
        $records = &$this->recordList->getList($this->areaRecord, $params);
        foreach ($records as &$record) {
            $areas[$record['id']] = $record['label'];
        }
        return array('start' => $event, 'legend' => 'addBannerForm',
                'submit' => 'add', 'items' => array(array('name' => 'area',
                'label' => 'area', 'type' => 'select', 'options' => $areas),
                array('name' => 'title', 'label' => 'title'), array('name' =>
                'viewsLeft', 'label' => 'viewsLeft'), array('name' => 'type',
                'label' => 'typeFlash', 'value' => 0, 'type' => 'radio'),
                array('name' => 'type', 'label' => 'typeImage', 'value' => 1,
                'type' => 'radio'),
                array('name' => 'flashSrc', 'label' => 'flashSrc'),
                array('name' => 'flashWidth', 'label' => 'flashWidth'),
                array('name' => 'flashHeight', 'label' => 'flashHeight'),
                array('name' => 'flashClass', 'label' => 'flashClass'),
                array('name' => 'flashQuality', 'label' => 'flashQuality'),
                array('name' => 'flashWMode', 'label' => 'flashWMode'),
                array('name' => 'flashMenu', 'label' => 'flashMenu'),
                array('name' => 'link', 'label' => 'link')));
    }
}
?>
